package com.backend.springboot_project_demo.service;

import com.backend.springboot_project_demo.common.Result;
import com.backend.springboot_project_demo.entity.*;
import com.backend.springboot_project_demo.utils.JwtUtils;
import com.backend.springboot_project_demo.utils.RedisUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UsageService {
    private final static String LOGIN_KEY = "login";

    private @Resource AddUserService addUserService;
    private @Resource AuthenticationManager authenticationManager;
    private @Resource RedisUtils<String, UserTransfer> redisUtils;
    private @Resource SearchRoleService searchRoleService;

    public Result<?> login(Usage usage) {
        // 用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(usage.getUsername(), usage.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果认证没有通过，给出相应的提示
        if (Objects.isNull(authenticate)) {
            return Result.fail("用户不存在，请查证后重新输入");
        }
        // 认证通过生成jwt
        UserTransfer userTransfer = (UserTransfer) authenticate.getPrincipal();
        Role role = searchRoleService.findById(userTransfer.getRoleId());
        String roleName = role.getName();
        List<String> permissions = role.getPermissions().stream().map(Permission::getName).collect(Collectors.toList());
        userTransfer.setRole(roleName);
        userTransfer.setPermissions(permissions);
        String userId = userTransfer.getId();
        String jwt = JwtUtils.crateJwt(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        redisUtils.hPut(LOGIN_KEY, userId, userTransfer);
        return Result.success(map);
    }

    public Result<?> logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserTransfer userTransfer = (UserTransfer) authentication.getPrincipal();
        String userId = userTransfer.getId();
        redisUtils.hDel(LOGIN_KEY, userId);
        return Result.success("登出成功");
    }

    public Result<?> register(UserTransfer userTransfer) {
        User user = userTransfer.toAddUser();
        if (user.isPassValidation()) {
            boolean result = addUserService.addUser(userTransfer.toAddUser());
            return result ? Result.success() : Result.fail("注册失败，请检查输入内容");
        } else {
            return Result.fail("注册失败，请检查网络后重试");
        }
    }
}
